<template>
  <el-form :model="form"
           :rules="rules"
           class="user-management-form"
           ref="form"
           v-loading="loading">
    <el-tooltip :open-delay="1000"
                effect="dark"
                :content="$t('user.tooltipcontent')"
                placement="top">
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item :label="$t('user.username')"
                        prop="username">
            <el-input v-model="form.username"
                      :disabled="form.id"
                      :placeholder="$t('user.username')"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item class="email"
                        prop="email"
                        :label="$t('user.email')">
            <el-input v-model="form.email"
                      :disabled="form.id"
                      :placeholder="$t('user.email')"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('user.firstName')"
                        prop="firstName">
            <el-input v-model="form.firstName"
                      :disabled="form.id"
                      :placeholder="$t('user.firstName')"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('user.lastName')"
                        prop="lastName">
            <el-input v-model="form.lastName"
                      :disabled="form.id"
                      :placeholder="$t('user.lastName')"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('user.displayName')"
                        prop="realName">
            <el-input v-model="form.realName"
                      :disabled="form.id"
                      :placeholder="$t('user.displayName')"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Password"
                        prop="password">
            <el-input v-model="form.password"
                      :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('user.mobile')"
                        prop="mobile">
            <el-input v-model="form.mobile"
                      :disabled="form.id"
                      :placeholder="$t('user.mobile')"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('user.businessPhones')"
                        prop="businessPhones">
            <el-input v-model="form.businessPhones"
                      :disabled="form.id"
                      :placeholder="$t('user.businessPhones')"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-tooltip>
    <el-divider content-position="left">JOB INFORMATION</el-divider>
    <el-row :gutter="24">
      <el-col :span="12">
        <el-form-item :label="$t('user.managerName')">
          <el-select v-model="form.managerId"
                     :disabled="form.id"
                     style="width:100%;"
                     filterable
                     clearable
                     default-first-option
                     :placeholder="$t('user.managerName')">
            <el-option v-for="user in managers"
                       :key="user.id"
                       :label="`${user.username} (${user.email})`"
                       :value="user.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('user.deptName')"
                      v-if="!isMe">
          <ren-dept-tree v-model="form.deptId"
                         :placeholder="$t('dept.title')"
                         :dept-name.sync="form.deptName"></ren-dept-tree>
        </el-form-item>
      </el-col>

    </el-row>
    <el-divider content-position="left">ACCOUNT INFORMATION</el-divider>
    <el-row :gutter="24">
      <el-col :span="24">
        <el-form-item prop="roleIdList"
                      :label="$t('user.roleIdList')">
          <el-select v-model="roleIds"
                     multiple
                     collapse-tags
                     style="width:100%"
                     :disabled="isMe"
                     :placeholder="$t('user.roleIdList')">
            <el-option v-for="(role, index) in fullRoles"
                       :key="index"
                       :label="role.name"
                       :value="role.roleId"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item>
          <ZCardSwitch label="Status"
                       :active-value="1"
                       :inactive-value="0"
                       :disabled="isMe"
                       v-model="form.status"
                       @change="statusChange"
                       desc="After a user's account is suspended, that user will not be able to log in." />
        </el-form-item>

      </el-col>
      <el-col :span="12">
        <el-form-item>
          <ZCardSwitch label="Message"
                       :disabled="disabledUser"
                       v-model="form.teamsMessageSwitch"
                       desc="After closing the message, the user's teams will no longer receive messages from MSPbots.ai." />
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item :label="$t('user.homeChannel')">
          <div style="position:relative;z-index: 99999;">
            <el-input v-model="homeChannelinput"
                      @input="channelInput"
                      @focus="channelFocus"
                      @blur="channelBlur"
                      ref="channel-input"
                      clearable
                      :placeholder="$t('user.homeChannel')"></el-input>
            <div class="custom-collapse-css card-css scroll-css"
                 v-if="setChannelStatus"
                 @click="clickChannelCard">
              <el-collapse accordion
                           v-model="activeNames">
                <el-collapse-item v-for="(value, key) in teamsChannelList"
                                  :key="key"
                                  :name="key">
                  <template slot="title">
                    {{ key }}
                  </template>
                  <template v-for="(it, j) in value">
                    <div :key="j">
                      <el-radio v-model="form.homeChannel"
                                :label="it.channelId">{{ it.displayName }}</el-radio>
                    </div>
                  </template>
                </el-collapse-item>
              </el-collapse>
            </div>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item v-if="$hasPermission('sys:report:homepage')"
                      :label="$t('custom.component.viewComponent.homepage')">
          <el-select v-model="form.homePage"
                     style="width:100%;"
                     filterable
                     clearable
                     :placeholder="$t('custom.component.viewComponent.homepage')">
            <el-option v-for="item in reports"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-divider content-position="left">
      THIRD-PARTY PLATFORM MAPPING
    </el-divider>

    <el-row :gutter="24">
      <el-col :span="12">
        <el-form-item v-if="connectorSetting['CW']"
                      prop="cwUserMapping"
                      :label="$t('user.cwUserMapping')">
          <el-select v-model="form.cwUid"
                     style="width:100%;"
                     filterable
                     :disabled="disabledUser"
                     default-first-option
                     :placeholder="$t('user.cwUserMapping')">
            <el-option v-for="item in mappings.cwUserList"
                       :key="item.cwUid"
                       :label="item.email"
                       :value="item.cwUid">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item v-if="connectorSetting['TEAMS']"
                      prop="teamsUserMapping"
                      :label="$t('user.teamsUserMapping')">
          <el-select v-model="form.teamsUserId"
                     style="width:100%;"
                     filterable
                     :disabled="disabledUser"
                     default-first-option
                     :placeholder="$t('user.teamsUserMapping')">
            <el-option v-for="item in mappings.teamsUserList"
                       :key="item.teamsUserId"
                       :label="item.teamsMail"
                       :value="item.teamsUserId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item v-if="connectorSetting['TSHEET']"
                      prop="sheetsUserMaapping"
                      :label="$t('user.sheetsUserMaapping')">
          <el-select v-model="form.sheetUserId"
                     style="width:100%;"
                     filterable
                     :disabled="disabledUser"
                     default-first-option
                     :placeholder="$t('user.sheetsUserMaapping')">
            <el-option v-for="item in mappings.sheetsUserList"
                       :key="item.sheetUserId"
                       :label="item.email"
                       :value="item.sheetUserId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item v-if="connectorSetting['TD']"
                      prop="timeDoctorUserMapping"
                      :label="$t('user.timeDoctorUserMapping')">
          <el-select v-model="form.timedoctorUser"
                     style="width:100%;"
                     filterable
                     :disabled="disabledUser"
                     default-first-option
                     :placeholder="$t('user.timeDoctorUserMapping')">
            <el-option v-for="item in mappings.timedoctorUserList"
                       :key="item.userId"
                       :label="item.email"
                       :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item v-if="connectorSetting['AUTOTASK']"
                      prop="autotaskUserMapping"
                      :label="$t('user.autotaskUserMapping')">
          <el-select v-model="form.autotaskUser"
                     style="width:100%;"
                     filterable
                     :disabled="disabledUser"
                     default-first-option
                     :placeholder="$t('user.autotaskUserMapping')">
            <el-option v-for="item in mappings.autotaskUserList"
                       :key="item.userId"
                       :label="item.email"
                       :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
import ZCardSwitch from '@/components/storybook/z-card-switch'
import qs from 'qs'

export default {
  name: 'UserAddForm',
  components: {
    ZCardSwitch
  },
  props: {
    connectorSetting: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    const validatePassword = (rule, value, callback) => {
      if (!this.form.id && !/\S/.test(value)) {
        return callback(new Error(this.$t('validate.required')))
      }
      callback()
    }

    const validateConfirmPassword = (rule, value, callback) => {
      if (!this.form.id && !/\S/.test(value)) {
        return callback(new Error(this.$t('validate.required')))
      }
      if (this.form.password !== value) {
        return callback(new Error(this.$t('user.validate.confirmPassword')))
      }
      callback()
    }
    return {
      form: {
        password: '0*HzMe@1972Z',
        confirmPassword: '0*HzMe@1972Z',
        gender: 0,
        roleIdList: [],
        status: 1
      },
      rules: {
        username: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        deptName: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'change'
          }
        ],
        regSource: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'change'
          }
        ],
        firstName: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        lastName: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        password: [{ validator: validatePassword, trigger: 'blur' }],
        confirmPassword: [
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
        realName: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ]

      },
      loading: false,
      reports: [],
      roles: [],
      mappings: {
        cwUserList: [],
        teamsUserList: [],
        sheetsUserList: [],
        timedoctorUserList: [],
        autotaskUserList: []
      },
      assignRoles: [],
      managers: []
    }
  },
  computed: {
    fullRoles () {
      return this.roles.filter(i => this.assignRoles.some(record => record.assignId === i.roleId))
    }
  },
  created () {
    this.init()
  },
  methods: {
    async init () {
      try {
        this.loading = true
        const [reports, roles, mappings, assignRoles, managers] = await Promise.all([this.getReports(), this.getRoles(), this.getMappings(), this.getAssignRoles(), this.getManagers()])

        this.reports = reports
        this.roles = roles
        this.mappings = mappings
        this.assignRoles = assignRoles
        this.managers = managers
      } catch (error) {

      } finally {
        this.loading = false
      }
    },
    async getReports () {
      const params = {
        queryType: 'REFRESHCACHE',
        layoutType: 'report_layout',
        showAllIntegration: false,
        resourceType:0
      }
      const { getReportCardList } = this.$interface.reports
      const { data: response } = getReportCardList(params)
      if (response.code !== 0) {
        throw response.msg
      }
      return response.data || []
    },
    async getRoles () {
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      const { getClientRoleListApi } = this.$interface.system
      const { data: response } = getClientRoleListApi(params)
      if (response.code !== 0) {
        throw response.msg
      }
      return response.data || []
    },
    async getMappings () {
      const params = {

      }

      const { getUserMappingListApi } = this.$interface.taskManager
      const { data: response } = getUserMappingListApi(params)
      if (response.code !== 0) {
        throw response.msg
      }
      return response.data || {}
    },
    async getAssignRoles () {
      let roleList = this.$store.state.user.roleList || []
      let roleId = roleList.map(i => i.id)
      const params = qs.stringify(
        {
          roleId: roleId
        },
        { arrayFormat: 'repeat' }
      )

      const { getAssignRoleList } = this.$interface.um
      const { data: response } = getAssignRoleList(params)
      if (response.code !== 0) {
        throw response.msg
      }
      return response.data || []
    },
    async getManagers () {
      const params = {
        tenantCode: this.dataForm.tenantCode
      }

      const { getUserManagerListApi } = this.$interface.system
      const { data: response } = getUserManagerListApi(params)
      if (response.code !== 0) {
        throw response.msg
      }
      return response.data || []
    }

  }
}
</script>
